import {log} from "@/util/Log.js"

let debug = true
let connection = null
let open =  false
let timeout = null

function init(token,fun){
    let protocol = 'ws://';
    if (window.location.protocol === 'https:') {
        protocol = 'wss://';
    }
    if (!window.WebSocket) {
        //否则报错
        consol("不支持 socket 连接")
        return;
    }
    try {
        let host = window.location.hostname+":"+8088
        // let host = window.location.hostname+":"+8080
        let endpoint = protocol + host + '/webSocket?token=' + token;
        connection = new WebSocket(endpoint);
    }catch (e){
        console.error(e)
    }
    // 打开连接
    connection.onopen = () => {
        open = true;
        consol("连接打开成功")
        // 自己维护心跳
        heartbeat()
        if(fun){
            fun(connection)
        }
    };

    // 接收消息
    connection.onmessage = (message) => {
        consol(message)
        let json = JSON.parse(message.data);
        if(json.type === 'ping'){
            heartbeat();
            return
        }
    };

    // 关闭连接
    connection.onclose = (evt) => {
        close(evt)
    };

    // 连接错误
    connection.onerror = (evt) => {
        consol(evt)
    };

}

function heartbeat(){
    let msg = {
        type: "ping",
    }
    timeout = setTimeout(() =>{
        connection.send(JSON.stringify(msg));
    },10000)
}

function send(msg){
    connection.send(JSON.stringify(msg));
}

function close(){
    clearInterval(timeout)
    connection.close()
}

function consol(msg){
    if(debug){
        log.info(msg)
    }
}

export default{
    connection,init,send,close
}